<template>
  <el-dialog v-model="dialogVisible" title="修改密码" width="500px" draggable>
    <el-form ref="roleFormRef" label-suffix=" :" :rules="rules" :model="item">
      <el-form-item label="旧密码" prop="oldPwd">
        <el-input type="password" v-model="item.oldPwd" placeholder="请填写旧密码" clearable></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="pwd">
        <el-input type="password" v-model="item.pwd" placeholder="请填写新密码" clearable></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref } from "vue";
import { updatePwdApi } from "@/api/modules/login";
import { ElMessage, FormInstance } from "element-plus";
import { useUserStore } from "@/stores/modules/user";

const dialogVisible = ref(false);
const openDialog = () => {
  dialogVisible.value = true;
};

let item = ref({
  pwd: "",
  oldPwd: ""
});
const rules = reactive({
  pwd: [{ required: true, message: "请填写新密码" }],
  oldPwd: [{ required: true, message: "请填写旧密码" }]
});
const userStore = useUserStore();
const roleFormRef = ref<FormInstance>();
const handleSubmit = () => {
  roleFormRef.value!.validate(async valid => {
    if (!valid) return;
    try {
      await updatePwdApi(item.value);
      userStore.setToken("");
      ElMessage.success("密码修改成功！");
    } catch (error) {
      console.log(error);
    }
  });
};

defineExpose({ openDialog });
</script>
